<template>
  <!--新增人员-->
  <el-dialog
    title="新增人员"
    :visible.sync="formVisible"
    :close-on-click-modal="false"
    @close="handleClose"
    custom-class="brand-dialog-min-width"
    width="640px"
    :modal-append-to-body="false"
    :append-to-body="true"
  >
    <el-form
      :model="formData"
      label-width="150px"
      class="mrT8"
      :rules="formRules"
      ref="formData"
    >
      <el-form-item label="人员姓名：" prop="name" class="row-padding-bottom">
        <!-- <el-input v-model="formData.name" autocomplete="off"></el-input> -->
        <el-autocomplete
          class="el-input dialogSingleInp"
          id="autocompleteInput"
          v-model="formData.name"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入人员姓名"
          @select="handleSelect"
          :trigger-on-focus="false"
        >
          <template slot-scope="{ item }">
            <div class="name">
              {{ item.value }}
              <span class="fr">{{ item.idcard }}</span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="身份证号：" class="row-padding-bottom" prop="idcard">
        <el-input
          v-model="formData.idcard"
          autocomplete="off"
          class="dialogSingleInp"
          placeholder="输入人员姓名后自动带入"
          disabled="disabled"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="tel" class="row-padding-bottom">
        <el-input
          v-model="formData.tel"
          class="dialogSingleInp"
          @blur="formData.tel = changeValue($event)"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="工资卡号："
        prop="account"
        class="row-padding-bottom"
      >
        <el-input
          v-model="formData.account"
          class="dialogSingleInp"
          @blur="formData.account = changeValue($event)"
          maxlength="64"
          placeholder="请输入工资卡号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="应发工资（元）："
        prop="shouldPay"
        class="row-padding-bottom"
      >
        <el-input
          v-model="formData.shouldPay"
          class="dialogSingleInp"
          @blur="formData.shouldPay = changeValue($event)"
          placeholder="请输入应发工资"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注：" class="row-padding-bottom">
        <el-input
          type="textarea"
          placeholder="如应发工资超过2万，可进行备注"
          v-model="formData.remark"
          @blur="formData.remark = changeValue($event)"
          maxlength="200"
          show-word-limit
          rows="3"
          class="dialogSingleInp"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="handleClose" class="cancel">取消</el-button>
      <el-button
        type="primary"
        @click.native="addPeopleSubmit"
        class="save"
        :loading="isLoading"
        >提交</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'addSalaryEmplyee',
  data() {
    return {
      formData: {
        //添加人员数据
        name: '',
        idcard: '',
        shouldPay: '',
        tel: '',
        account: '',
        remark: '',
        companyName: '',
        groupId: '',
        groupName: '',
        attDays: '',
        year: this.year,
        month: this.month,
        projectName: this.projectName,
        projectId: this.projectId,
      },
      formRules: {
        //添加人员表单验证
        name: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入人员姓名',
            trigger: 'change',
          },
        ],
        idcard: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请选中项目中已有的人员',
            trigger: 'change',
          },
        ],
        tel: [
          {
            // required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        account: [
          {
            required: true,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入正确格式的账号',
            trigger: 'blur',
          },
        ],
        shouldPay: [
          {
            required: true,
            message: '请输入应发工资金额!',
            trigger: 'blur',
          },
          {
            pattern: /^\d{1,7}(\.\d{0,2})?$/,
            message: '已超过金额最大值，请重新输入',
            trigger: 'blur',
          },
        ],
      },
      restaurants: [], //人员姓名
      isLoading: false,
    }
  },
  props: {
    formVisible: {
      type: Boolean,
      default: false,
    },
    projectId: { type: String, default: '' },
    year: { type: String, default: '' },
    month: { type: String, default: '' },
    salaryId: { type: String, default: '' },
    projectName: { type: String, default: '' },
  },
  watch: {
    formVisible(val) {
      if (val) {
        this.formData = {
          name: '',
          idcard: '',
          shouldPay: '',
          tel: '',
          account: '',
          remark: '',
          companyName: '',
          groupId: '',
          groupName: '',
          attDays: '',
          year: this.year,
          month: this.month,
          projectName: this.projectName,
          projectId: this.projectId,
        }
      }
    },
    'formData.name': {
      handler(newVal, oldVal) {
        if (this.isIE9) {
          // ie9的操作
          if (oldVal) {
            if (newVal != oldVal) {
              this.clearTimer()
              this.timer = setTimeout(function () {
                $('#autocompleteInput').blur()
                $('#autocompleteInput').focus()
              }, 5000)
            }
          }
        }
      },
      deep: true,
      // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
      // immediate: true
    },
  },
  methods: {
    //关闭弹窗
    closeDialog() {
      this.$refs['formData'].resetFields()
    },
    //人员姓名
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants
      this.methodaa(queryString, cb, restaurants)
    },
    methodaa(queryString, cb, restaurants) {
      var that = this
      that.getEmployeesForAddSalary().then(function (result) {
        if (result) {
          restaurants = that.loadAll(result)

          that.restaurants = restaurants

          let results = queryString
            ? restaurants.filter(that.createFilter(queryString))
            : restaurants
          cb(results)
          // do sth.
        } else {
          // do other sth.
        }
      })
    },
    createFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          // state.value
        )
      }
    },
    async getEmployeesForAddSalary() {
      var list = ''
      var data = {
        search: this.formData.name,
        projectId: this.projectId, //项目ID
        year: this.year,
        month: this.month,
        // year 年
        // month  月
      }
      await this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/salaryemp',
        data: data,
      })
        .then(
          (response) => {
            list = response.data.result
          },
          (response) => {}
        )
        .catch((error) => {})
      return list
    },
    loadAll(data) {
      let serier = []
      if (data) {
        for (let i = 0, l = data.length; i < l; i++) {
          let item = data[i]

          serier.push({
            value: item.name,
            idcard: item.idcard,
            employeeId: item.employeeId,
            uscc: item.uscc,
            companyName: item.companyName,
            groupId: item.groupId,
            groupName: item.groupName,
            attDays: item.attDays,
            account: item.account,
            tel: item.tel,
          })
        }
      } else {
        // 如果没有请求到数据，则显示暂无数据！
        serier.push({ str: '暂无数据' })
      }
      return serier
    },
    handleSelect(item) {
      this.formData.name = item.value
      this.formData.idcard = item.idcard
      this.formData.employeeId = item.employeeId
      ;(this.formData.uscc = item.uscc),
        (this.formData.companyName = item.companyName),
        (this.formData.groupId = item.groupId),
        (this.formData.groupName = item.groupName),
        (this.formData.attDays = item.attDays)
      this.formData.account = item.account || ''
      this.formData.tel = item.tel || ''
    },
    handleClose() {
      this.finished()
      this.$refs['formData'].resetFields()
    },
    //弹窗保存
    addPeopleSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.addPeople()
        } else {
          return false
        }
      })
    },
    addPeople() {
      var data = { salaryId: this.salaryId }
      this.formData.account = this.formData.account.replace(/\s+/g, '')
      data = Object.assign(data, this.formData)

      this.axios({
        method: 'post',
        url: 'api-su/cs/salarydetail/expand/add',
        data: data,
      })
        .then((response) => {
          this.isLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '添加成功',
              type: 'success',
            })
            this.finished(1)
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'warning',
            })
          }
        })
        .catch((error) => {
          this.isLoading = false
        })
    },
    finished(index) {
      this.$emit('callback', { success: index == 1 ? true : false })
    },
  },
}
</script>
<style lang="less" scoped>
.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
</style>
